package com.ctgu.server.service.impl;


import com.ctgu.server.components.exceptions.BizException;
import com.ctgu.server.dao.constant.CacheKey;
import com.ctgu.server.service.ValidateCodeService;
import net.oschina.j2cache.CacheObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import net.oschina.j2cache.CacheChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Autowired
    private CacheChannel cacheChannel;    //操作缓存
    @Override
    public void create(String key, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(key)) {
            throw BizException.validFail("验证码key不能为空");
        }
      /*  Captcha captcha=new ArithmeticCaptcha();
        String text= captcha.text();
        //将验证码进行缓存
        cacheChannel.set(CacheKey.CAPTCHA,key,text);*/

        //将生成的验证码图片通过输出流写回客户端页面
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        response.setHeader(HttpHeaders.PRAGMA, "No-cache");
        response.setHeader(HttpHeaders.CACHE_CONTROL, "No-cache");
        response.setDateHeader(HttpHeaders.EXPIRES, 0L);   //防止浏览器缓存数据

        //本次产生的验证码
        Captcha captcha = new ArithmeticCaptcha(115, 42);
        captcha.setCharType(2);


        //将字符全部转换成小写
        cacheChannel.set(CacheKey.CAPTCHA, key, StringUtils.lowerCase(captcha.text()));
        captcha.out(response.getOutputStream());
    }

    @Override
    public boolean check(String key, String code) {
        if(StringUtils.isBlank(key)){
            throw BizException.validFail("验证码key不能为空");
        }
        //根据key可以从缓存中获取验证码
        CacheObject cacheObject=cacheChannel.get(CacheKey.CAPTCHA,key);
        if(cacheObject.getValue()==null){
            throw BizException.validFail("验证码key已经过期");
        }
        String codeInCache=(String) cacheObject.getValue();
        if(!codeInCache.equals(code)){
            throw BizException.validFail("验证码错误");
        }
        //验证码成功后立即清理验证码
        //验证通过，立即从缓存中删除验证码
        cacheChannel.evict(CacheKey.CAPTCHA, key);
        return true;
    }

//    @Override
//    public void buildCacheKey(String captcha, String uuid) {
//        cacheChannel.set(CacheKey.UUID_KEY,uuid,uuid);
//    }
}
